package ua.dp.md05.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import ua.dp.md05.Product;
import ua.dp.md05.Product_;
import ua.dp.md05.dao.common.AbstractDaoBean;

@Stateless
public class ProductDaoBean extends AbstractDaoBean<Product> implements
        ProductDao {

	@Inject
	private Logger log;

	@Override
	public List<Product> find(int maxresults, int firstresult) {
		log.info("find product, max results " + maxresults + " next result " + firstresult);

		CriteriaBuilder builder = getCriteriaBuilder();
		CriteriaQuery<Product> query = builder.createQuery(Product.class);

		Root<Product> from = query.from(Product.class);
		query.select(from).orderBy(builder.desc(from.get(Product_.created)));
		return getResultList(query, maxresults, firstresult);
	}

	@Override
	public Long count() {
		CriteriaBuilder builder = getCriteriaBuilder();
		CriteriaQuery<Long> query = builder.createQuery(Long.class);
		Root<Product> from = query.from(Product.class);

		query.select(builder.count(from));

		return this.<Long> getTypedSingleResult(query);

	}

    @Override
    public Product findByBarcode(String barcode) {
        CriteriaBuilder builder = getCriteriaBuilder();
        CriteriaQuery<Product> query = builder.createQuery(Product.class);
        Root<Product> from = query.from(Product.class);
        query.select(from).where(builder.equal(from.get(Product_.barcode), barcode));

        List<Product> resultList = getResultList(query);
        return resultList.isEmpty() ? null : resultList.get(0);
    }
}
